﻿using Newtonsoft.Json;
using ReservationChecker.Models;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net;

namespace ReservationChecker.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        const string apiUrl = @"http://xnumber.azurewebsites.net/api/webservice";

        public MainViewModel()
        {
            this.Items = new ObservableCollection<ItemViewModel>();
        }

        // A collection for ItemViewModel objects.
        public ObservableCollection<ItemViewModel> Items { get; private set; }

        public bool IsDataLoaded
        {
            get;
            set;
        }

        // Creates and adds a few ItemViewModel objects into the Items collection.
        public void LoadData()
        {
            if (this.IsDataLoaded == false)
            {
                this.Items.Clear();
                this.Items.Add(new ItemViewModel() { LineOne = DateTime.Now, LineTwo = "Please wait while information is downloaded from the server." });
                WebClient webClient = new WebClient();
                webClient.Headers["Accept"] = "application/json";
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadSummaryCompleted);
                webClient.DownloadStringAsync(new Uri(apiUrl));

            }
        }

        private void webClient_DownloadSummaryCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                this.Items.Clear();
                if (e.Result != null)
                {
                    var bookings = JsonConvert.DeserializeObject<DailySummary[]>(e.Result);

                    foreach (DailySummary booking in bookings)
                    {
                        this.Items.Add(new ItemViewModel()
                        {
                            LineOne = booking.Date,
                            LineTwo = "Total reservations: " + booking.NumReservations,
                            LineThree = "Seating required: " + booking.NumSeats,
                        });
                    }
                    this.IsDataLoaded = true;

                }
            }
            catch //(Exception ex)    //Provides far more detailed error message beyond user scope.
            {
                this.Items.Add(new ItemViewModel()
                {
                    // Displays error message in LongListSelector binding
                    LineOne = DateTime.Now,
                    LineTwo = "An error has occured whilst trying to retrive data from the server.",  // More user friendly error message
                    //LineTwo = String.Format("The following exception occured: {0}", ex.Message),
                    //LineThree = String.Format("Additional inner exception information: {0}", ex.InnerException.Message)
                });
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}